<script lang="ts">
import { onMount } from "svelte";
import type { Event as EventType } from "$lib/Database/SB/events.js";
import type { Group as GroupType } from "$lib/Database/SB/groups.js";
import Event from "$lib/Events/Event.svelte";
import Group from "$lib/Events/Group.svelte";
import Spacer from "$lib/Layout/Spacer.svelte";
import Message from "$lib/Loading/Message.svelte";
import root from "$lib/Utility/root";
import locale from "$stores/locale";
import type { PageData } from "./$types";

export let data: PageData;

let groupsResponse: Promise<Response>;

onMount(async () => {
	groupsResponse = fetch(root(`/api/events/group?slug=${data.group}`));
});

const asGroup = (group: unknown) => group as GroupType;

const asEvent = (event: unknown) => event as EventType;
</script>

{#await groupsResponse}
  <Message message={$locale().events?.loadingGroup} />
{:then group}
  {#if group}
    {#await group.json()}
      <Message message={$locale().events?.parsingGroup} />
    {:then json}
      {#if json === null}
        <Message message="" loader="ripple" slot>
          {$locale().events?.groupNotExistPrefix}
          <a href={'#'} onclick={() => location.reload()}>{$locale().common?.tryAgain}</a>{$locale().events?.groupNotExistSuffix}
        </Message>
      {:else}
        {@const group = asGroup(json)}

        <Group {group} />

        <Spacer />

        <details open>
          <summary>{$locale().events?.summary}</summary>

          {#await fetch(root(`/api/events?group=${data.group}`))}
            <Message message={$locale().events?.loadingEvents} />
          {:then eventsResponse}
            {#await eventsResponse.json()}
              <Message message={$locale().events?.parsingEvents} />
            {:then events}
              {#if events}
                {#each events as rawEvent, i}
                  <Event event={asEvent(rawEvent)} />

                  {#if i < events.length - 1}
                    <Spacer />
                  {/if}
                {/each}
              {/if}
            {:catch}
              <Message message="" loader="ripple" slot withReload>{$locale().events?.errorParsingEvents}</Message>
            {/await}
          {/await}
        </details>
      {/if}
    {:catch}
      <Message message="" loader="ripple" slot withReload>{$locale().events?.errorParsingGroup}</Message>
    {/await}
  {:else}
    <Message message={$locale().events?.parsingGroups} />
  {/if}
{:catch}
  <Message message="" loader="ripple" slot withReload>{$locale().events?.errorLoadingGroup}</Message>
{/await}
